<template>
  <div class="parking-status-container">
    <van-nav-bar title="我的车位情况" />
    <!-- 状态指示模块 -->
    <van-cell-group inset>
      <van-cell title="当前状态">
        <template #value>
          <van-tag :type="statusConfig.type">{{ statusConfig.label }}</van-tag>
        </template>
      </van-cell>

      <!-- 动态信息展示 -->
      <template v-if="currentStatus !== STATUS.unbooked">
        <van-cell
          v-for="(item, index) in list"
          :key="index"
          :title="item.label"
          :value="item.value"
        />
      </template>
    </van-cell-group>

    <!-- 操作按钮 -->
    <div class="action-area">
      <van-button
        block
        :type="buttonConfig.type"
        @click="handleMainAction"
      >
        {{ buttonConfig.text }}
      </van-button>
      <template v-if="currentStatus === STATUS.unbooked">
        <van-button
          style="margin-top: 10px"
          block
          type="success"
          @click="oneStepToOrder"
        >
          一键预约
        </van-button>
        <van-notice-bar
          style="margin: 5px 0; height: 20px"
          color="#1989fa"
          background="#ffffff"
          left-icon="info-o"
        >
          当前距离最近的停车位为：{{ bestSpot?.spotNumber ? bestSpot.spotNumber : "-" }}
        </van-notice-bar>
      </template>
      <template v-if="currentStatus === STATUS.booked">
        <van-button
          style="margin-top: 10px"
          block
          type="danger"
          @click="toCancelReserve"
        >
          取消预约
        </van-button>
      </template>
 
    </div>

    <!-- 缴费确认弹窗 -->
    <van-dialog
      v-model:show="showPaymentDialog"
      title="缴费确认"
      show-cancel-button
      @confirm="confirmPayment"
    >
      <div class="payment-content">
        <p>停车时长：{{ formattedDuration }}</p>
        <p class="fee-amount">需支付：¥{{ calculatedFee || 0 }}</p>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onUnmounted, onMounted } from 'vue'
import { showNotify } from 'vant'
import { getCurrentMessage } from '@/api/reservation.js'
import { startToSpot, endToSpot } from '@/api/record.js'
import { quickOrder, nearestSpot } from '@/api/spot.js'
import { cancelReserve } from '@/api/reservation.js'
import { useUserStore } from '@/stores/userStore'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()

// 状态常量
const STATUS = {
  unbooked: 0,
  booked: 1,
  parking: 2
}

// 时间间隔常量
const UPDATE_INTERVAL = 10 * 1000

// 状态管理
const currentStatus = ref(STATUS.unbooked)
const startTimestamp = ref(null)
const timer = ref(null)
const showPaymentDialog = ref(false)
const myTimer = ref(null)

// 计时逻辑
const duration = ref(0)

// 启动计时器
const startTimer = () => {
  if (startTimestamp.value) {
    timer.value = setInterval(() => {
      duration.value = Math.floor((Date.now() - startTimestamp.value) / 1000)
    }, 1000)
  }
}

const list = ref([])
const currentId = ref(null)

// 状态配置计算
const statusConfig = computed(() => {
  const configMap = {
    [STATUS.unbooked]: {
      label: '未预约',
      type: 'primary'
    },
    [STATUS.booked]: {
      label: '已预约',
      type: 'warning'
    },
    [STATUS.parking]: {
      label: '停车中',
      type: 'danger'
    }
  }
  return configMap[currentStatus.value]
})

// 按钮配置计算
const buttonConfig = computed(() => {
  const configMap = {
    [STATUS.unbooked]: {
      text: '预约车位',
      type: 'primary'
    },
    [STATUS.booked]: {
      text: '开始停车',
      type: 'warning'
    },
    [STATUS.parking]: {
      text: `立即缴费 ¥${calculatedFee.value || 0}`,
      type: 'danger'
    }
  }
  return configMap[currentStatus.value]
})

// 时间格式化
const formattedDuration = computed(() => {
  const hours = Math.floor(duration.value / 3600)
  const minutes = Math.floor((duration.value % 3600) / 60)
  return `${hours}小时${minutes}分钟`
})

// 费用计算（5元/小时，最低5元）
const calculatedFee = ref(0)

// 主操作处理
const handleMainAction = () => {
  switch (currentStatus.value) {
  case STATUS.unbooked:
    router.push('/index')
    break
  case STATUS.booked:
    toStartToSpot()
    break
  case STATUS.parking:
    showPaymentDialog.value = true
    break
  }
}

// 缴费确认
const confirmPayment = () => {
  toEndToSpot()
  clearInterval(timer.value)
  currentStatus.value = STATUS.unbooked
  duration.value = 0
  startTimestamp.value = null
}

// 初始化界面
const getCurrent = async () => {
  const res = await getCurrentMessage({ userId: userStore.userInfo?.id })
  if (res.code === 0) {
    const tempData = res.data
    if (tempData?.status === STATUS.unbooked) {
      currentStatus.value = STATUS.unbooked
    }
    clearList()
    if (tempData?.status === STATUS.booked) {
      list.value.push({ label: '车位编号', value: tempData?.spot })
      list.value.push({ label: '保留剩余时间', value: tempData?.time + '分钟' })
      currentId.value = tempData?.reservationId
      currentStatus.value = STATUS.booked
    }
    if (tempData?.status === STATUS.parking) {
      currentId.value = tempData?.recordId
      duration.value = tempData?.duration
      calculatedFee.value = tempData?.fee
      startTimestamp.value = tempData?.startTime
      list.value.push({ label: '开始时间', value: formatTimestamp(tempData?.startTime) })
      list.value.push({ label: '停车时长', value: formattedDuration.value })
      list.value.push({ label: '费用', value: (tempData?.fee ? tempData.fee : 0) + '元' })
      currentStatus.value = STATUS.parking
      startTimer()
    }
  } else {
    showNotify({ type: 'danger', message: '获取当前状态失败...' })
  }
}

// 点击开始停车
const toStartToSpot = async () => {
  const res = await startToSpot({ reservationId: currentId.value })
  if (res.code === 0) {
    clearList()
    await getCurrent()
  } else {
    showNotify({ type: 'danger', message: '开始停车操作失败' })
  }
}

// 点击结束停车
const toEndToSpot = async () => {
  const res = await endToSpot({ recordId: currentId.value })
  if (res.code === 0) {
    clearList()
    await getCurrent()
  } else {
    showNotify({ type: 'danger', message: '结束停车操作失败' })
  }
}

// 清空列表
const clearList = () => {
  list.value = []
}

// 时间戳格式化
const formatTimestamp = (timestamp) => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}:${month}:${day} ${hours}:${minutes}:${seconds}`
}

// 一键预约
const oneStepToOrder = async() => {
  const res = await quickOrder({ userId: userStore.userInfo?.id })
  if (res.code === 0) {
    clearList()
    await getCurrent()
  }
}

// 最近的车位
const bestSpot = ref(null)

// 获取最近的车位
const getNearestSpot = async () => {
  const res = await nearestSpot()
  if (res.code === 0) {
    bestSpot.value = res.data
  }
}

// 取消预约
const toCancelReserve = async () => {
  const res = await cancelReserve({ reservationId: currentId.value })
  if (res.code === 0) {
    if (res.data === 2) {
      userStore.onLogout()
      router.push('/login')
      return
    }
    clearList()
    await getCurrent()
  }
}

onMounted(() => {
  getNearestSpot()
  getCurrent()
  myTimer.value = setInterval(getCurrent, UPDATE_INTERVAL)
})

// 清理计时器
onUnmounted(() => {
  if (timer.value) clearInterval(timer.value)
  if (myTimer.value) clearInterval(myTimer.value)
})
</script>

<style scoped>
.parking-status-container {
  padding: 16px;
}

.action-area {
  margin-top: 24px;
  padding: 0 16px;
}

.payment-content {
  padding: 16px;
  text-align: center;
}

.payment-content .fee-amount {
  font-size: 18px;
  color: #ee0a24;
  font-weight: bold;
  margin-top: 8px;
}
</style>